package com.campusbackend.mapper;

import com.campusbackend.entity.NewsManagement;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

/**
 * <p>
 * 新闻管理表 Mapper 接口
 * </p>
 *
 * @author yezi
 * @since 2025-07-29
 */
@Mapper
public interface NewsManagementMapper extends BaseMapper<NewsManagement> {

    /**
     * 分页查询新闻（管理端）
     * @param page 分页对象
     * @param status 状态筛选（可选）
     * @return 分页结果
     */
    @Select("<script>" +
            "SELECT n.*, a.real_name as publisherName FROM news_management n " +
            "LEFT JOIN admin_users a ON n.publisher_id = a.id " +
            "WHERE n.status != -1 " +
            "<if test='status != null'>" +
            "AND n.status = #{status} " +
            "</if>" +
            "ORDER BY n.publish_time DESC, n.create_time DESC" +
            "</script>")
    IPage<NewsManagement> selectPageWithStatus(Page<NewsManagement> page, @Param("status") Integer status);

    /**
     * 根据ID查询新闻详情（不包括已删除的）
     * @param id 新闻ID
     * @return 新闻详情
     */
    @Select("SELECT n.*, a.real_name as publisherName FROM news_management n " +
            "LEFT JOIN admin_users a ON n.publisher_id = a.id " +
            "WHERE n.id = #{id} AND n.status != -1")
    NewsManagement selectByIdNotDeleted(Long id);

    /**
     * 增加浏览次数
     * @param id 新闻ID
     * @return 更新行数
     */
    @Update("UPDATE news_management SET view_count = view_count + 1 WHERE id = #{id}")
    int incrementViewCount(Long id);

    /**
     * 软删除新闻（设置状态为-1）
     * @param id 新闻ID
     * @return 更新行数
     */
    @Update("UPDATE news_management SET status = -1, update_time = NOW() WHERE id = #{id}")
    int softDeleteById(Long id);
}
